package cn.wolfcode.p2p.business.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.wolfcode.p2p.base.domain.Account;
import cn.wolfcode.p2p.base.exception.DisplayableException;
import cn.wolfcode.p2p.base.service.IAccountService;
import cn.wolfcode.p2p.base.util.Constants;
import cn.wolfcode.p2p.base.util.UserContext;
import cn.wolfcode.p2p.business.domain.BidRequest;
import cn.wolfcode.p2p.business.domain.CreditTransfer;
import cn.wolfcode.p2p.business.mapper.CreditTransferMapper;
import cn.wolfcode.p2p.business.query.CreditTransferQueryObject;
import cn.wolfcode.p2p.business.service.IAccountFlowService;
import cn.wolfcode.p2p.business.service.IBidRequestService;
import cn.wolfcode.p2p.business.service.ICreditTransferService;

@Service
@Transactional
public class CreditTransferServiceImpl implements ICreditTransferService {

	@Autowired
	private CreditTransferMapper creditTransferMapper;

	@Autowired
	private IBidRequestService bidRequestService;

	@Autowired
	private IAccountService accountService;

	@Autowired
	private IAccountFlowService flowService;

	private void update(CreditTransfer ct) {
		int count = this.creditTransferMapper.updateByPrimaryKey(ct);
		if (count == 0) {
			System.out.println("乐观锁异常,creditTransfer:" + ct.getId());
			throw new DisplayableException("系统繁忙,请重试");
		}
	}

	@Override
	public PageInfo<CreditTransfer> query(CreditTransferQueryObject qo) {
		PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
		List<CreditTransfer> list = this.creditTransferMapper.queryData(qo);
		return new PageInfo<>(list);
	}

	@Override
	public PageInfo<CreditTransfer> listCanTransferCredit(CreditTransferQueryObject qo) {
		PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
		List<CreditTransfer> list = this.creditTransferMapper.listCanTransferCredit(UserContext.getCurrent().getId());
		return new PageInfo<>(list);
	}

	@Override
	public void creditTransfer(Long[] bidId) {
		if (bidId != null) {
			List<CreditTransfer> readyForCreates = this.creditTransferMapper
					.listReadyToTransferCredit(UserContext.getCurrent().getId(), bidId);
			for (CreditTransfer item : readyForCreates) {
				item.setBidRequestState(Constants.BIDREQUEST_STATE_BIDDING);
				item.setTransFrom(UserContext.getCurrent());
				item.setPublishDate(new Date());
				this.creditTransferMapper.insert(item);
				this.creditTransferMapper.changePaymentScheduleDetailTransState(item.getBidId(), Constants.IN_TRANS);
			}
		}
	}

	@Override
	public void subscribe(Long id) {
		CreditTransfer ct = this.creditTransferMapper.selectByPrimaryKey(id);
		BidRequest oldBr = this.bidRequestService.get(ct.getBidRequestId());
		Account subscriberAccount = this.accountService.get(UserContext.getCurrent().getId());
		// 判断,
		if (ct != null//
				&& ct.getBidRequestState() == Constants.BIDREQUEST_STATE_BIDDING// 1,招标中状态;
				&& !subscriberAccount.getId().equals(oldBr.getCreateUser().getId())// 2,当前用户不是原借款的借款人
				&& !subscriberAccount.getId().equals(ct.getTransFrom().getId())// 也不是转让人;
				&& subscriberAccount.getUsableAmount().compareTo(ct.getBidRequestAmount()) >= 0// 3,当前余额>=认购本金
		) {
			// 执行认购
			// 1,设置债权标的相关属性;
			ct.setTransTo(UserContext.getCurrent());
			ct.setTransDate(new Date());
			ct.setBidRequestState(Constants.BIDREQUEST_STATE_COMPLETE_PAY_BACK);
			this.update(ct);
			// 对于认购人
			// 1,可用余额减少;生成认购流水
			subscriberAccount.setUsableAmount(subscriberAccount.getUsableAmount().subtract(ct.getBidRequestAmount()));
			this.flowService.createSubscribeFlow(subscriberAccount, ct);
			// 2,待收本金增加;待收利息增加;
			subscriberAccount
					.setUnReceiveInterest(subscriberAccount.getUnReceiveInterest().add(ct.getRemainInterest()));
			subscriberAccount
					.setUnReceivePrincipal(subscriberAccount.getUnReceivePrincipal().add(ct.getBidRequestAmount()));
			this.accountService.update(subscriberAccount);
			// 对于转让人
			Account transAccount = this.accountService.get(ct.getTransFrom().getId());
			// 1,可用余额增加;生成转让流水;
			transAccount.setUsableAmount(transAccount.getUsableAmount().add(ct.getBidRequestAmount()));
			this.flowService.createTransferFlow(transAccount, ct);
			// 2,待收本金减少;待收利息减少;
			transAccount.setUnReceivePrincipal(transAccount.getUnReceivePrincipal().subtract(ct.getBidRequestAmount()));
			transAccount.setUnReceiveInterest(transAccount.getUnReceiveInterest().subtract(ct.getRemainInterest()));
			this.accountService.update(transAccount);
			// 其他
			// 1,还款明细收款人改变;
			this.creditTransferMapper.changePaymentScheduleDetailInvestor(ct.getBidId(),
					UserContext.getCurrent().getId());
			// 2,还款明细Instrans状态改变;
			this.creditTransferMapper.changePaymentScheduleDetailTransState(ct.getBidId(), Constants.NOT_IN_TRANS);
		}
	}

	@Override
	public CreditTransfer findNeedCancel(Long bidId) {
		return this.creditTransferMapper.findNeedCancel(bidId);
	}

	@Override
	public void cancel(CreditTransfer cancel) {
		cancel.setBidRequestState(Constants.BIDREQUEST_STATE_UNDO);
		this.update(cancel);
		this.creditTransferMapper.changePaymentScheduleDetailTransState(cancel.getBidId(), Constants.NOT_IN_TRANS);
	}

}
